package sally

import (
	"fmt"
	"time"

	"gitee.com/leonscript/sally/v2/domain/aggregate"
	"gitee.com/leonscript/sally/v2/infrastructure/persistent"
	"gitee.com/leonscript/sally/v2/infrastructure/referenceimpl"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func Init(db *gorm.DB, hook aggregate.Hook) (result aggregate.ClerkService, err error) {
	err = db.AutoMigrate(
		&persistent.WorkflowTemplate{},
		&persistent.NodeTemplate{},
		&persistent.NodeTemplateReviewer{},

		&persistent.Workflow{},
		&persistent.Node{},
		&persistent.NodeReviewerTask{},
	)

	// 初始化sally
	reference := referenceimpl.NewClerkReferenceImpl(db)
	result = aggregate.NewClerkService(reference, hook)

	return result, err
}

func connect(c Config) (result *gorm.DB, err error) {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%v)/%s?charset=utf8&parseTime=True&loc=Local",
		c.User, c.Password,
		c.Host, c.Port,
		c.Schema)

	db, err := gorm.Open(mysql.New(mysql.Config{
		DSN:                       dsn,
		DisableDatetimePrecision:  true,
		DontSupportRenameIndex:    true,
		DontSupportRenameColumn:   true,
		SkipInitializeWithVersion: false,
	}))
	if err != nil {
		panic("init db fail:" + err.Error())
	}

	// 维护连接池
	sqlDB, err := db.DB()
	if err != nil {
		return result, err
	}

	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(c.MaxIdleConns)

	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(c.MaxOpenConns)

	// SetConnMaxLifetime 设置了连接可复用的最大时间。
	sqlDB.SetConnMaxLifetime(time.Duration(c.ConnMaxLifetime) * time.Minute)

	return db, err
}

type Config struct {
	Host            string
	Port            string
	User            string
	Password        string
	Schema          string
	MaxIdleConns    int
	ConnMaxLifetime int64
	MaxOpenConns    int
}
